
package com.scalar.chiptrack.operations.packingslip.actions;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import java.util.Date;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Collections;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;

import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.Customer;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;

import com.scalar.ScalarException;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;

import com.scalar.chiptrack.operations.packingslip.FinalInventoryData;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLotNumberData;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLineItem;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.dao.CommercialInvoiceDAO;

public class DropShipmentPSAction extends ChipTrackAction{

    private static String ERROR_MESSAGE_CONTACT_SYS_ADMN = "Please.. Contact <a href='javascript:showErrorReportPage()'>System Administrator</a>";

    private HashMap m_errors = null;

    public DropShipmentPSAction()
	{
        m_errors = new HashMap();
    }

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
    {

		String returnVal = "failure";
		String action = request.getParameter("action");
		if (action == null)
		{
			action = "newPackingSlip";
		}

        request.setAttribute( "AUTO_CONFIRM_PACKING_SLIP", request.getParameter ("autoConfirmPackingSlip") );

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, "/packingSlip.do?" + request.getQueryString());
			return (mapping.findForward("login"));
        }
        String currentUser = user.getUserId();


		// CANCEL THIS PACKING SLIP
		if ("cancelPackingSlip".equalsIgnoreCase (action))
		{
			PackingSlipForm dropShipmentPSForm = (PackingSlipForm) form;
			int customerShippingId = dropShipmentPSForm.getCustomerShippingId();
			DBTransaction dbTransaction = null;
			boolean success = false;
            try
			{
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();

				PackingSlipDAO.cancelPackingSlip (dbTransaction,customerShippingId);
				CommercialInvoiceDAO.deleteCommercialInovice(dbTransaction,customerShippingId);
				success = true;
				HashMap info = new HashMap();
				info.put ("Drop Shipment PackingSlip (" + dropShipmentPSForm.getLabel() + ") has been cancelled", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
			}
			catch (ScalarException se) {
				HashMap errors = new LinkedHashMap();
				errors.put ("Internal Server Error", "Could not cancel packingslip (" + dropShipmentPSForm.getLabel() + ")");
				errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);

				session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not cancel packingslip (" + dropShipmentPSForm.getLabel() + ")" );
				session.setAttribute( SessionKeys.ERROR_REPORT, se );
				request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
			}
			finally
			{
    			if (success == true)
				{
					dbTransaction.commit();
				}
				else
				{
					dbTransaction.rollback();
				}
            }
            return (mapping.findForward ("dropShipmentView"));
		}


		// CONFIRM THIS PACKING SLIP 
		if ("confirmPackingSlip".equalsIgnoreCase (action))
		{
			PackingSlipForm packingSlipForm = (PackingSlipForm) form;
			int customerShippingId = packingSlipForm.getCustomerShippingId();
			int noOfBoxes =  packingSlipForm.getNoOfBoxesAsInt();
			String shippedVia =  packingSlipForm.getShippedVia();
			String weight = packingSlipForm.getWeight();
			String grossWeight = packingSlipForm.getGrossWeight();
			String contactPerson = packingSlipForm.getContactPerson();
			String invoiceNo = packingSlipForm.getInvNo();
			String shipDate = packingSlipForm.getShipDate();
			String[] tracking =  packingSlipForm.getTracking();

            try
			{
				PackingSlipDAO.confirmPackingSlip ( customerShippingId, noOfBoxes, tracking, currentUser, shippedVia, weight, contactPerson, invoiceNo, shipDate, grossWeight );
				HashMap info = new HashMap();
				info.put ("PackingSlip (" + packingSlipForm.getLabel() + ") has been issued", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
            }
            catch (ScalarException se)
			{
				HashMap errors = new LinkedHashMap();
				errors.put ("Internal Server Error", "Could not confirm packingslip (" + packingSlipForm.getLabel() + ")");
				errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);
                request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not confirm packingslip (" + packingSlipForm.getLabel() + ")" );
                session.setAttribute( SessionKeys.ERROR_REPORT, se );
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            return (mapping.findForward ("packingSlipMenu"));
        }

        // LOAD SALES ORDER INFORMATION
        if ("loadSalesOrder".equalsIgnoreCase(action))
		{
			session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );//added on 6 Nov 2003
			session.removeAttribute( "repeatedPartNumber" );
			session.removeAttribute( "orgFinalInventoryDataList" );
            try
			{
                String salesOrderId = request.getParameter ("salesOrderId");

                SalesOrder salesOrder = SalesOrderDAO.loadSalesOrder (salesOrderId);
                int total = PackingSlipDAO.getTotalNumberOfPackingSlipsGenerated (salesOrderId);

                Customer customer = CustomerDAO.loadCustomerById (salesOrder.getCustomerId());
                String shippedVia = "";
                if ( ( salesOrder.getShippingMethod() != null ) && ( salesOrder.getShippingMethod().trim().length() != 0 ) )
                {
                    if ( ( salesOrder.getShippingAccount() != null ) && ( salesOrder.getShippingAccount().trim().length() != 0 ) )
                    {
                        shippedVia = salesOrder.getShippingMethod() + "-" + salesOrder.getShippingAccount();
                    }
                    else
                    {
                        shippedVia = salesOrder.getShippingMethod();
                    }
                }
                else
                {
                    if ( ( salesOrder.getShippingAccount() != null ) && ( salesOrder.getShippingAccount().trim().length() != 0 ) )
                    {
                        shippedVia = salesOrder.getShippingAccount();
                    }
                    else
                    {
                        shippedVia = "";
                    }
                }
               // Create PackingSlipForm for the given salesOrderId and save it in request

			   PackingSlipForm dropShipmentPSForm = new PackingSlipForm (
                                                  "PS-" + salesOrder.getSalesOrderNo() + "-" + (total + 1), //+ "-" + (long)(Math.random()*10000000), //packing slip label
                                                  -1,   //customerShippingId
                                                  salesOrder.getSalesOrderId(),
                                                  salesOrder.getSalesOrderNo(),
                                                  salesOrder.getCustomerName(),
                                                  salesOrder.getCustomerPO(),
                                                  null/*salesOrder.getContactPerson()*/,
                                                  customer.getRepOffice(),
                                                  customer.getTerms(),
                                                  salesOrder.getDeliveryTerms(), //fob
                                                  null,   //noOfBoxes
                                                  null, //tracking
                                                  shippedVia,
                                                  salesOrder.getShippingMethod(),
                                                  salesOrder.getShippingAccount(),
                                                  salesOrder.getBillingAddress(),
                                                  salesOrder.getShippingAddress(),
                                                  salesOrder.getShippingInstructions());

                dropShipmentPSForm.setShippingToAddressId (salesOrder.getShippingAddressId());
                dropShipmentPSForm.setShipDate (StringUtils.formatDateToString (new Date(System.currentTimeMillis())));


                // add salesOrderId list to the session
                if (session.getAttribute("salesOrderIdList") == null) {
                    ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
                    session.setAttribute ("salesOrderIdList", ids);
                }

                // Load all packingslips generated for this sales order
                ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (Integer.parseInt(salesOrderId), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
                request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

                // Get CustomerShippingLineItems for this salesOrderId
                HashMap customerShippingLineItemMap = PackingSlipDAO.loadShippableLineItemMapBySalesOrderId (Integer.parseInt(salesOrderId));

                // Create OrderLineItems and save it in request
                HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (Integer.parseInt (salesOrderId), 0);
                if(orderLineItemMap.isEmpty() == true)
				{
                    //Put the errors message if there are no approved lineItems
                    HashMap m_errors = new HashMap();
                    m_errors.put ("No Approved LineItems left in this SalesOrder", null);
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
                }

				PackingSlipDAO.loadCustomerPartNumber( customerShippingLineItemMap, orderLineItemMap, salesOrder.getCustomerId() );
				request.setAttribute ("customerShippingLineItemMap", customerShippingLineItemMap);//this will now contain the customer part number also. 3 Jan 2004
				request.setAttribute ("locations", PackingSlipDAO.getFromAddressId());//added the new Locations field (Bhaskar 13 Jan 2004
                request.setAttribute("dropShipmentPSForm", dropShipmentPSForm);

                ArrayList orderLineItemList = new ArrayList();

                // Keep Line Items that are // added by hareesh on 9th July 2003
                java.util.Set setCsltKey = customerShippingLineItemMap.keySet();
                Object[] arrayCsltKey =  setCsltKey.toArray();
                java.util.Arrays.sort(arrayCsltKey);
                int length = arrayCsltKey.length;
                Object lineItemIdKey = null;
                for(int count=0; count < length; count++ )
				{
                    lineItemIdKey = arrayCsltKey[count];
                    if (orderLineItemMap.containsKey (lineItemIdKey) == true)
					{
                        orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                    }
                } // added by hareesh on 9th July 2003

				request.setAttribute ("orderLineItemList", orderLineItemList);

                // added by ravikanth on Nov 2,2003

				ArrayList repetedPartNumber = new ArrayList();

                if( orderLineItemList.size() > 1)
                {
	                for( int i=0 ; i < orderLineItemList.size()-1 ; i++ )
    	            {
						LineItem lineItem = (LineItem) orderLineItemList.get(i);
						String partNumber = lineItem.getManufacturingPartNo();

						for(int j=i+1 ; j < orderLineItemList.size(); j++)
						{
							LineItem secLineItem = (LineItem) orderLineItemList.get(j);

							String secPartNumber = secLineItem.getManufacturingPartNo();

							if(partNumber.equalsIgnoreCase(secPartNumber))
							{
								if( !repetedPartNumber.contains(lineItem.getLineItemId()+"") )
									repetedPartNumber.add(lineItem.getLineItemId()+"");
								if( !repetedPartNumber.contains(secLineItem.getLineItemId()+"") )
									repetedPartNumber.add(secLineItem.getLineItemId()+"");
							}
						}
               	 	}
                }
				if( repetedPartNumber.size() > 0 )
				{
					//system.out.println("I am having two part Numbers same  "+repetedPartNumber.size());
					session.setAttribute("repetedPartNumber",repetedPartNumber);
				}
				//request.setAttribute ("orderLineItemList", orderLineItemList);
                returnVal = "success";
            }
            catch (ScalarException se)
			{
                // Exception while accessing database
                // log it
                //system.out.println ("Exception while loading the sales order: " + se.getRootCause().getMessage());
                // add error
                HashMap m_errors = new HashMap();

                if (se.getRootCause().getMessage().indexOf ("No Line Items are pending") != -1)
				{
                    m_errors.put ("Sales order ID", "There are no pending line items to be shipped. Please select another Sales Order ID");
                }
                else
				{
                    m_errors.put ("Sales order ID", "Unable to load this sales order ID data <br>Please select another Sales Order ID");
                }
                request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
                m_errors = new HashMap();   // reset the errors hash-map
            }

			if (returnVal.equalsIgnoreCase("success"))
			{
				return (mapping.findForward (returnVal));
			}
            // There is a problem loading the sales order.. lets show the new packing slip screen
            request.removeAttribute("dropShipmentPSForm");
            action = "newPackingSlip";
        }

        // SAVE THE PACKING SLIP INFORMATION INTO DATABASE AND GENERATE PACKING SLIP With Shipped Status///////////////
		if ("save".equalsIgnoreCase (action))
		{
			//#ystem.out.println ("The save scope is reached");
			HashMap lineItemMap = null;
			HashMap finalInventoryMap = null;
			PackingSlipForm dropShipmentPSForm = (PackingSlipForm) form;
			m_errors = validateForm (dropShipmentPSForm, true);
			//system.out.println ("The form is validated and the m_errors hashmap size is : "+m_errors.size());

			// Valid form
			if ((m_errors == null) || (m_errors.isEmpty() == true))
			{
				try
				{
					// CHECK IF THERE ARE ANY ERRORS IN FINAL INVENTORY POP-UP WINDOW
					//#ystem.out.println ("There are no errors in the m_errors");
					//HashMap finalInventoryActionErrors = (HashMap) session.getAttribute ("FINAL_INVENTORY_ACTION_ERRORS");
					//session.removeAttribute ("FINAL_INVENTORY_ACTION_ERRORS");

					//if ((finalInventoryActionErrors != null) && (finalInventoryActionErrors.isEmpty() == false))
					//{
					//	m_errors.putAll (finalInventoryActionErrors);
					//}
					//else
					//{
					/*int fromLocationId = -1;
					try
					{
						fromLocationId = Integer.parseInt ((String) session.getAttribute (SessionKeys.SHIPPING_FROM_LOCATION_ID));
						//system.out.println ("From Location Id in the line 325 : "+fromLocationId);
					}
					catch (NumberFormatException nfe) {
						//ignore.
						//system.out.println ("There is no locationID");
					}*/
					//session.removeAttribute (SessionKeys.SHIPPING_FROM_LOCATION_ID);

					/*if (fromLocationId == -1)
					{
						//system.out.println ("OOPS from location ID is -1");
						//m_errors.put ("Couldnt save Packing Slip, Invalid values entered in Quantity Pull window", null);
					}*/
					//else
					//{
						//dropShipmentPSForm.setShippingFromLocationId (fromLocationId);
					lineItemMap = getLineItemsFromRequest (request);
						/*if( ( m_errors.isEmpty() ) && ( ( lineItemMap != null ) && ( lineItemMap.isEmpty() == false ) ) )
						{
							finalInventoryMap = (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP);
							if (finalInventoryMap == null)
							{
								m_errors.put ("Couldnt save Packing Slip, Invalid values entered in Quantity Pull window", null);
							}
							else
							{*/
					boolean confirmPackingSlip = true;
					//system.out.println ("about to call the method to save");
					int customerShippingId = PackingSlipDAO.saveDropShipmentCustomerShippingInfo (dropShipmentPSForm, Arrays.asList(lineItemMap.values().toArray()), finalInventoryMap, currentUser, confirmPackingSlip);
					// Remove the session attribute after updating the database
					// Balaram.. on June 12, 2003
					session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
					session.removeAttribute("repetedPartNumber");//remove the attribute that was set when the PS has two line items with same part number

					dropShipmentPSForm.setCustomerShippingId (customerShippingId);
					request.setAttribute ("SAVE_PACKING_SLIP", "yes");
					returnVal = "dropShipmentView";
							//}
						//}

						// check if the line items are selected
						// SHOW ERRORS
						/*if ((m_errors.isEmpty()) && ((lineItemMap == null) || (lineItemMap.isEmpty() == true)))
						{
							m_errors.put ("No line items", "Please select at least one Line Item");
						}*/
					//}
				//}
                }
                catch (ScalarException se)
				{
                    // couldnt save customer_shipping information
                    se.getRootCause().printStackTrace();
                    m_errors.put ("Couldnot save the drop shipment packing slip", null);
                }
            }
            // Load all packingslips generated for this sales order
            ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (dropShipmentPSForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
            request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

            // Get CustomerShippingLineItems for this salesOrderId
            if (returnVal.equalsIgnoreCase("dropShipmentView") != true)
			{
				lineItemMap = PackingSlipDAO.loadShippableLineItemMapBySalesOrderId (dropShipmentPSForm.getSalesOrderId());
            }
            request.setAttribute ("customerShippingLineItemMap", lineItemMap);  //customerShippingLineItemMap);

            // Create OrderLineItems and save it in request
            HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (dropShipmentPSForm.getSalesOrderId(), 0);
            ArrayList orderLineItemList = new ArrayList();

            // added by hareesh on 9th July 2003
            java.util.Set lineItemKey = lineItemMap.keySet();
            Object[] arrayLineTemKey =  lineItemKey.toArray();
            java.util.Arrays.sort(arrayLineTemKey);
            int length = arrayLineTemKey.length;
            Object lineItemIdKey = null;
            for(int count=0; count < length; count++ )
			{
                lineItemIdKey = arrayLineTemKey[count];
                if (orderLineItemMap.containsKey (lineItemIdKey) == true)
				{
					orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                }
            }
            if (returnVal.equalsIgnoreCase("dropShipmentView"))
			{
			    Collections.sort(orderLineItemList,new PackingSlipComparator());
            }

            request.setAttribute ("orderLineItemList", orderLineItemList);

            if (m_errors.isEmpty() == false)
			{
				request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
				//m_errors = new HashMap();
            }

			HashMap info = new HashMap();
			if ( m_errors.isEmpty() )
			{
				info.put ("PackingSlip (" + dropShipmentPSForm.getLabel() + ") has been issued", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
			}
            request.setAttribute ("showMainMenu", "true");
            return (mapping.findForward (returnVal));
        }



        // VIEW EXISTING PACKING SLIP 
		if (("view".equalsIgnoreCase (action)) || ("viewShipped".equalsIgnoreCase (action)))
		{
			session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
			request.setAttribute ("showNoModifyMessage", "TRUE");
			session.removeAttribute("repetedPartNumber");
			session.removeAttribute("orgFinalInventoryDataList");


			int customerShippingId = -1;
			//system.out.println("noOfBoxes : " + request.getParameter("noOfBoxes") +"tracking: " + request.getParameter("tracking") ) ;
			try
			{
				customerShippingId = Integer.parseInt ((String) request.getAttribute ("customerShippingId"));
			}
			catch (NumberFormatException nfe) {}

			if((String)request.getAttribute("customerShippingId") == null) //for viewShipped
                try{ customerShippingId = Integer.parseInt ((String) request.getParameter ("customerShippingId")); } catch (NumberFormatException nfe) {}

            int salesOrderId = -1;
            try
			{
				salesOrderId = Integer.parseInt ((String) request.getParameter ("salesOrderId"));
			}
			catch (NumberFormatException nfe) {}

			if ((customerShippingId != -1) && (customerShippingId != -2))
			{
				// create and save packingSlipForm
				boolean success = false;
				PackingSlipForm dropShipmentPSForm = null;
				try
				{
					dropShipmentPSForm = PackingSlipDAO.loadPackingSlipById (customerShippingId);
					if ( ( dropShipmentPSForm.getNoOfBoxes()=="0" ) || ( dropShipmentPSForm.getNoOfBoxes().equals("0") ) )
                    {
                        dropShipmentPSForm.setNoOfBoxes("");
                    }
                    else
                    {
						if (request.getParameter("noOfBoxes") != null)
						{
							dropShipmentPSForm.setNoOfBoxes(request.getParameter("noOfBoxes"));
						}
                    }
					if ( ( request.getParameter( "noOfBoxes" ) != null ) && ( request.getParameterValues( "tracking" ) != null ) )
					{
						dropShipmentPSForm.setNoOfBoxes( request.getParameter( "noOfBoxes" ) );
						String[] trackingNumbers = request.getParameterValues( "tracking" );
						if( ( trackingNumbers != null ) && ( trackingNumbers.length == 1 ) && ( trackingNumbers[0] != null ) && ( trackingNumbers[0].indexOf( ';' ) != -1 ) )
						{
							dropShipmentPSForm.setTracking( StringUtils.toStringArray( trackingNumbers[0], ";" ) );
						}
						else
						{
							dropShipmentPSForm.setTracking( trackingNumbers );
						}
					}
                    if( request.getParameter( "shippedVia" ) != null )
					{
						dropShipmentPSForm.setShippedVia( request.getParameter( "shippedVia" ) );
                    }
                    if( request.getParameter( "shipDate" ) != null)
					{
                        dropShipmentPSForm.setShipDate( request.getParameter( "shipDate" ) );
                    }
                    if( request.getParameter( "weight" ) != null)
					{
						try
						{
							dropShipmentPSForm.setWeight( request.getParameter( "weight" ).trim() );
						}
						catch(Exception ex){}
                    }
                    if( request.getParameter( "invNo" ) != null)
					{
						dropShipmentPSForm.setInvNo( request.getParameter( "invNo" ) );
                    }
                    if( request.getParameter( "contactPerson" ) != null)
					{
						dropShipmentPSForm.setContactPerson( request.getParameter( "contactPerson" ) );
                    }
					int getShippingFrmLocationId = PackingSlipDAO.getLocationIdFromAddressId(dropShipmentPSForm.getShippingFromAddressId());
					if ( getShippingFrmLocationId != -1 )
					{
						dropShipmentPSForm.setShippingFromLocationId(getShippingFrmLocationId);
					}
                    success = true;
                }
                catch (ScalarException se)
				{
					HashMap errors = new LinkedHashMap();
					errors.put ("Internal Server Error", "Could not load Packing Slip");
					errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);
                    // Balaram, on July 8, 2003
                    request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
                    session.setAttribute( SessionKeys.ERROR_REPORT, se );
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
				}

                if (success == true)
				{
					// add salesOrderId list to the session
					if (session.getAttribute("salesOrderIdList") == null)
					{
						ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
						session.setAttribute ("salesOrderIdList", ids);
					}
                    // save lineItems
                    HashMap customerShippingLineItemMap = dropShipmentPSForm.getLineItemMap();
                    request.setAttribute ("customerShippingLineItemMap", customerShippingLineItemMap);
                    session.setAttribute ("csLineItemMap", customerShippingLineItemMap);

                    // Load all packingslips generated for this sales order
                    ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (dropShipmentPSForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
                    request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);
					request.setAttribute ("locations", PackingSlipDAO.getFromAddressId());//added the new Locations field (Bhaskar 13 Jan 2004
                    // Create and save OrderLineItems
                    HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (dropShipmentPSForm.getSalesOrderId(),1);
                    ArrayList orderLineItemList = new ArrayList();

                    // Keep Line Items that are
                    // added by hareesh on 9th July 2003
                    java.util.Set setCsltKey = customerShippingLineItemMap.keySet();
                    Object[] arrayCsltKey =  setCsltKey.toArray();
                    java.util.Arrays.sort(arrayCsltKey);
                    int length = arrayCsltKey.length;
                    Object lineItemIdKey = null;
                    for(int count=0; count < length; count++ )
					{
						lineItemIdKey = arrayCsltKey[count];
                        if (orderLineItemMap.containsKey (lineItemIdKey) == true)
						{
                            orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                        }

					} // added by hareesh on 9th July 2003

//					added by ravikanth on Nov 2,2003

					ArrayList repetedPartNumber = new ArrayList();
					if( orderLineItemList.size() > 1)
					{
						for( int i=0 ; i < orderLineItemList.size()-1 ; i++ )
						{
							LineItem lineItem = (LineItem) orderLineItemList.get(i);
							String partNumber = lineItem.getManufacturingPartNo();

							for(int j=i+1 ; j < orderLineItemList.size(); j++)
							{
								LineItem secLineItem = (LineItem) orderLineItemList.get(j);

								String secPartNumber = secLineItem.getManufacturingPartNo();

								if(partNumber.equalsIgnoreCase(secPartNumber))
								{
									if( !repetedPartNumber.contains(lineItem.getLineItemId()+"") )
										repetedPartNumber.add(lineItem.getLineItemId()+"");
									if( !repetedPartNumber.contains(secLineItem.getLineItemId()+"") )
										repetedPartNumber.add(secLineItem.getLineItemId()+"");
								}
							}
						}
					}
					if( repetedPartNumber.size() > 0 )
					{
						//system.out.println("I am having two part Numbers same  "+repetedPartNumber.size());
						session.setAttribute("repetedPartNumber",repetedPartNumber);
					}

					request.setAttribute ("dropShipmentPSForm", dropShipmentPSForm);
                    request.setAttribute ("orderLineItemList", orderLineItemList);
                    request.setAttribute ("action", "viewPackingSlip");
                    if("viewShipped".equalsIgnoreCase (action))
					{
                        return (mapping.findForward ("updateForInv"));
                    }
					else
					{
                        return (mapping.findForward (returnVal));
                    }
                }
                else
				{
                    // Failed to load packing slip by id
                    // Goto New packing slip screen
                    action = "newPackingSlip";
                }
            }
            else if (salesOrderId != -1)
			{
                action = "loadSalesOrder";
            }
            else
			{
                if (customerShippingId == -2)  // Confirm the packingslip automatically after saving it.
				{
                    request.setAttribute ("AUTO_CONFIRM_PACKING_SLIP", "true");
                }
                action = "newPackingSlip";  // goto newPackingSlip screen
            }
        }


        // UPDATE EXISTING PACKING SLIP ////////////////////////////////
        if ("updatePackingSlip".equalsIgnoreCase (action))
		{
            HashMap lineItemMap = null;
            HashMap finalInventoryMap = null;
            PackingSlipForm dropShipmentPSForm = (PackingSlipForm) form;
			String[] tracking =  dropShipmentPSForm.getTracking();
            m_errors = validateForm (dropShipmentPSForm, false);
            // Valid form
            if ((m_errors == null) || (m_errors.isEmpty() == true))
			{
                try
				{
					lineItemMap = getLineItemsFromRequest (request);
                    if ((m_errors.isEmpty()) && ((lineItemMap != null) && (lineItemMap.isEmpty() == false)))
					{
                        finalInventoryMap = (HashMap) session.getAttribute (SessionKeys.FINAL_INVENTORY_MAP);
                        PackingSlipDAO.updateDropShipmentCustomerShippingInfo (dropShipmentPSForm, Arrays.asList(lineItemMap.values().toArray()), finalInventoryMap, currentUser);
                        session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
                        request.setAttribute ("UPDATE_PACKING_SLIP", "yes");
                        returnVal = "dropShipmentView";
                    }
                }
                catch (ScalarException se)
				{
                    // couldnt update customer_shipping information
                    se.getRootCause().printStackTrace();
                    m_errors.put ("Could not save the packing slip", null);
                }
            }

            // Load all packingslips generated for this sales order
            ArrayList packingSlipListBySalesOrderId = PackingSlipDAO.loadPackingSlipsBySalesOrderId (dropShipmentPSForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED);
            request.setAttribute ("packingSlipListBySalesOrderId", packingSlipListBySalesOrderId);

            // Show line items
			//system.out.println ("Line 460 in DSPSA : "+returnVal);
            if (returnVal.equalsIgnoreCase("packingSlipView") != true)
			{
                lineItemMap = (HashMap) session.getAttribute ("csLineItemMap");
                if (lineItemMap == null) lineItemMap = new HashMap();
            	    session.removeAttribute ("csLineItemMap");
            }

            request.setAttribute ("customerShippingLineItemMap", lineItemMap);

            // Create and save OrderLineItems
            HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (dropShipmentPSForm.getSalesOrderId(), 1);
            if (orderLineItemMap == null) orderLineItemMap = new HashMap();

            ArrayList orderLineItemList = new ArrayList();

            // added by hareesh on 9th July 2003
            java.util.Set lineItemKey = lineItemMap.keySet();
            Object[] arrayLineTemKey =  lineItemKey.toArray();
            java.util.Arrays.sort(arrayLineTemKey);
            int length = arrayLineTemKey.length;
            Object lineItemIdKey = null;
            for(int count=0; count < length; count++ )
			{
                lineItemIdKey = arrayLineTemKey[count];
                if (orderLineItemMap.containsKey (lineItemIdKey) == true)
				{
                    orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                }
            } // added by hareesh on 9th July 2003


            // added by ravikanth on 20 Aug 2003 for sorting by PO Line Item
            Collections.sort(orderLineItemList,new PackingSlipComparator());
            request.setAttribute ("orderLineItemList", orderLineItemList);

            if (m_errors.isEmpty() == false)
			{
                request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
                m_errors = new HashMap();
                request.setAttribute ("action", "viewPackingSlip");
            }


			HashMap info = new HashMap();
			if ( m_errors.isEmpty() )
			{
				info.put ("PackingSlip (" + dropShipmentPSForm.getLabel() + ") has been shipped", null);
				//info.put ("Shipped Drop Shipments can be viewed from Packing Slip", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
			}
            request.setAttribute ("showMainMenu", "true");
			//system.out.println ("PADAO line 719 : "+returnVal);
            return (mapping.findForward (returnVal));
        }


		//UPDATE PACKING SLIP FOR ONLY INV NO AND AIRWAY BILL NO -- Added by Kumar Achanala
        if("updateInvNoAndAirwayBillNo".equalsIgnoreCase(action))
		{
            PackingSlipForm packingSlipForm = (PackingSlipForm) form;
            PackingSlipDAO.updateCustomerShippingForInvNo( packingSlipForm, currentUser );
            HashMap errors = new HashMap();
            errors.put("Packing Slip Details", "Saved Successfully");
            // Report any errors we have discovered back to the original form
            if(!errors.isEmpty())
                request.setAttribute(SessionKeys.INFO_MESSAGES, errors);

            request.setAttribute ("showMainMenu", "true");
            return (mapping.findForward ("packingSlipMenu"));
        }

        // PACKING SLIP - PRINTABLE FORMAT ////////////////////////////////
        if ("printView".equalsIgnoreCase (action))
		{
            request.setAttribute ("confirmPackingSlip", request.getParameter("confirmPackingSlip"));
            request.setAttribute ("cancelPackingSlip", request.getParameter("cancelPackingSlip"));
            request.setAttribute ("showMainMenu", request.getParameter("showMainMenu"));
            /*Bhaskar added this attribute to show the no_modify message on non
             printer friendly view on 30 july 2003*/
            request.setAttribute ("showNoModifyMessage", "FALSE");

            int customerShippingId = -1;
            try
			{
                customerShippingId = Integer.parseInt ((String) request.getParameter ("customerShippingId"));
            }
            catch (NumberFormatException nfe)
			{
                // Invalid or no value
            }

            if (customerShippingId != -1)
			{
                // create and save packingSlipForm
                boolean success = false;
                PackingSlipForm packingSlipForm = null;
                try
				{
                    packingSlipForm = PackingSlipDAO.loadPackingSlipById (customerShippingId);
                    if ( ( packingSlipForm.getNoOfBoxes()=="0" ) || ( packingSlipForm.getNoOfBoxes().equals("0") ) )
                    {
                        packingSlipForm.setNoOfBoxes("");
                    }
                    success = true;
                }
                catch (ScalarException se)
				{
                    HashMap errors = new LinkedHashMap();
                    errors.put ("Internal Server Error", "Could not load Packing Slip");
                    errors.put (ERROR_MESSAGE_CONTACT_SYS_ADMN, null);
                    // Balaram, on July 8, 2003
                    request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
                    session.setAttribute( SessionKeys.ERROR_REPORT, se );
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                }

                if (success == true)
				{
                    request.setAttribute ("packingSlipForm", packingSlipForm);
                    // add salesOrderId list to the session
                    if (session.getAttribute("salesOrderIdList") == null)
					{
                        ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
                        session.setAttribute ("salesOrderIdList", ids);
                    }

                    // save lineItems
                    HashMap customerShippingLineItemMap = packingSlipForm.getLineItemMap();
                    request.setAttribute ("customerShippingLineItemMap", customerShippingLineItemMap);

                    // Create and save OrderLineItems
                    HashMap orderLineItemMap = PackingSlipDAO.loadOpenOrderLineItemMap (packingSlipForm.getSalesOrderId(), 1);
                    ArrayList orderLineItemList = new ArrayList();

                     // added by hareesh on 9th July 2003
                    java.util.Set setCsltKey = customerShippingLineItemMap.keySet();
                    Object[] arrayCsltKey =  setCsltKey.toArray();
                    java.util.Arrays.sort(arrayCsltKey);
                    int length = arrayCsltKey.length;
                    Object lineItemIdKey = null;
                    for(int count=0; count < length; count++ )
					{
                        lineItemIdKey = arrayCsltKey[count];
                        if (orderLineItemMap.containsKey (lineItemIdKey) == true)
						{
                            orderLineItemList.add (orderLineItemMap.get (lineItemIdKey));
                        }
                    }

					// added by ravikanth on 20 Aug 2003 for sorting by PO Line Item
					Collections.sort(orderLineItemList,new PackingSlipComparator());
                    request.setAttribute ("orderLineItemList", orderLineItemList);
                }
            }

            return (mapping.findForward ("dropShipmentPrintView"));
        }


        // OPEN NEW PACKING SLIP ////////////////////////////////
        if ("newPackingSlip".equalsIgnoreCase(action))
		{
            try
			{
                if (session.getAttribute("salesOrderIdList") == null)
				{
                    ArrayList ids = SalesOrderDAO.loadAllSalesOrderIdAndCustomerPOs();
                    session.setAttribute ("salesOrderIdList", ids);
                }

                returnVal = "success";
            }
            catch (ScalarException se)
			{
                // Exception while accessing database
                // log it
                se.getRootCause().printStackTrace();
            }
        }

        return (mapping.findForward ("success"));
    }//end of execute method.


    private HashMap getLineItemsFromRequest (HttpServletRequest request) {

        HashMap lineItems = new HashMap();

        int lineItemCount = Integer.parseInt (request.getParameter ("lineItemCount"));

        int lineItemId = -1;
        int lineItemNumber = -1;
        int quantityShipped = 0;
        int quantityRequested = 0;
        int previousQuantityShipped = 0;
        int pendingQuantity = 0;
        String description = null;
        String softwareVersion = null;
		String units = null;//Bhaskar added on 28 Jan 2004
        String customerPartNumber = null;//Bhaskar added on 16 December 2003

        CustomerShippingLineItem lineItem = null;
        for (int i=0; i<lineItemCount; i++) {

            // see if this line_item is selected or not
            String selected = request.getParameter ("select_" + i);

            if (selected == null) {
                continue;
            }

            try {
                lineItemId = Integer.parseInt (request.getParameter ("lineItemId_"+i));
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Line Item ID", "Invalid Line Item ID.. " + request.getParameter ("lineItemId_"+i));
            }

            try {
                lineItemNumber = Integer.parseInt (request.getParameter ("lineItemNumber_"+i));
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Line Item Number", "Invalid Line Item Number.. " + request.getParameter ("lineItemNumber_"+i));
            }


            try {
                quantityRequested = Integer.parseInt (request.getParameter ("quantityRequested_"+i));
            }
            catch (NumberFormatException nfe) {
                m_errors.put ("Requested Quantity", "Invalid value for Requested Quantity.. " + request.getParameter ("quantityRequested_"+i));
            }

            try {
                previousQuantityShipped = Integer.parseInt (request.getParameter ("previousQuantityShipped_"+i));
            }
            catch (NumberFormatException nfe) {
                //no value
            }

            try {

                quantityShipped = Integer.parseInt (request.getParameter ("quantityShipped1_"+i));

                if (quantityShipped <= 0) {
                    m_errors.put ("Quantity Shipped (Line Item: " + lineItemNumber + ")", "-ve value is entered for Quantity Shipped.. " + quantityShipped);
                }

                pendingQuantity = (quantityRequested - (quantityShipped - previousQuantityShipped));

                if (pendingQuantity < 0) {
                    m_errors.put ("Quantity Shipped (Line Item: " + lineItemNumber + ")", "Cannot ship more quantity than requested.");
                }
            }
            catch (NumberFormatException nfe) {
				nfe.printStackTrace();
                m_errors.put ("Quantity Shipped (Line Item: " + lineItemNumber + ")", "Invalid value entered for Quantity Shipped.. " + request.getParameter ("quantityShipped_"+i));
            }
            //added by vasu on 22 May 2003
                description = request.getParameter ("description_"+i);
                //system.out.println ("description = " + description );
                units = request.getParameter ("units_"+i);
				customerPartNumber = request.getParameter("customerPartNumber_"+i);//Bhaskar added on 16 December 2003

            if (m_errors.isEmpty() == false) {
                continue;
            }

            int csLineItemId = -1;
            try {
                csLineItemId = Integer.parseInt (request.getParameter ("id_" + i));
            }
            catch (NumberFormatException nfe) {
                // invalid or no line item ID
            }

            String shippedDate = request.getParameter ("shippedDate_" + i);
            lineItem = new CustomerShippingLineItem (lineItemId, quantityShipped, pendingQuantity, shippedDate,description,softwareVersion);
            lineItem.setId (csLineItemId);
			lineItem.setCustomerPartNumber(customerPartNumber);//Bhaskar added on 16 December 2003
			lineItem.setUnits(units);//Bhaskar added on 28 Jan 2004
            lineItems.put (lineItemId + "", lineItem);
        }
        return lineItems;
    }


    private HashMap validateForm (PackingSlipForm packingSlipForm, boolean checkLabel) throws ScalarException {

        HashMap errors = new HashMap();

        if (packingSlipForm == null) {
            errors.put ("Internal Server Error occured while processing the request", null);

            return errors;
        }

        if (checkLabel == true) {
            String label = packingSlipForm.getLabel();
            if ((label == null) || (label.trim().length() == 0)) {
                errors.put ("Label", "Packingslip Label is invalid");
            }
            else if (PackingSlipDAO.doesPackingSlipLabelExist (label) == true) {
                errors.put ("Label", "Packing Slip Label, " + label + " already exists");
            }
        }

        try {
            String noOfBoxes = packingSlipForm.getNoOfBoxes();
            if ((noOfBoxes != null) && (noOfBoxes.trim().length() != 0)) {
                Integer.parseInt (packingSlipForm.getNoOfBoxes());
            }
        }
        catch (NumberFormatException nfe) {
            errors.put ("No Of Boxes", "Not a number, please enter a valid number");
        }

        String shipDate = packingSlipForm.getShipDate();
        if ((shipDate == null) || (shipDate.trim().length() == 0)) {
            errors.put ("Ship Date", "Please enter a valid Ship Date");
        }


        return errors;
    }


    public String formatAsHTML (String host, PackingSlipForm packingSlipForm, ArrayList orderLineItemList, HashMap csLineItemMap, HashMap finalInventoryMap) {

        StringBuffer buf = new StringBuffer (2098);

        //Changed by hareesh on 29th August 2003
        // -- START --
        String backgroundImage = "";
        if (Constants.CUSTOMER_SHIPPING_STATUS_CANCELLED.equalsIgnoreCase (packingSlipForm.getStatus())) {
            backgroundImage = "http://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/cancelled_icon.gif";
        }
        // -- END --

        buf.append ("<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>\n");
        buf.append ("<link href='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/stylesheets/scalarsoft.css' type='text/css' rel='stylesheet'>\n");
        buf.append ("</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>\n");
        //buf.append ("<TABLE cellSpacing=0 cellPadding=0 width='70%' border='0' >\n");
        //buf.append ("<TR><td width='180' valign='top' background='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/left_red_bg.gif'>\n");
        //buf.append ("<TD bgcolor='#ffffff'><IMG height=9 src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' width=8></TD>\n");
        //buf.append ("<TD bgcolor='#ffffff'><IMG height=480 src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' width=2></TD>\n");
        //buf.append ("<TD valign='top' width='100%'><IMG height=1 src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/clear.gif' width=500 border=0><BR>\n");
        buf.append ("<!-- body starts -->\n");

        //buf.append ("<img src='http://" + host + "/" +ConfigManager.getChipTracContext() +"/jsp/includes/images/scalar_logo.jpg' width=180 height=72 border=0>\n");
        //buf.append ("<center><span class='NArialW'><h2>Packing Slip</h2></span></center>\n");
        //buf.append ("<BR>\n");

        //buf.append ("<table border='0' width='90%' align='center'  background=''>\n");
        buf.append ("<table border='0' width='90%' align='center'  background='"+backgroundImage+"'>\n"); //Changed by hareesh on 29th August 2003
        //buf.append ("<td width='21%'><font class='NArialL'>PackingSlip Label: </font></td>\n");
        buf.append ("<tr><td align='center'>");
        buf.append ("<table width='100%' border='0' class='NArialR' bordercolor='#000000' cellspacing='0'>");
            buf.append ("<TR><td width='35%' align='center'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/scalar_logo.jpg' height='120' width='200' border='0' ></td>");
            //buf.append ("<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'></td>");
            buf.append ("<td width='35%' align='center' class='NArialL'><font class='NArialW'>Packing Slip </font><br>" +  ConfigManager.getClientAddressLine1());
            buf.append ("<br>"+ ConfigManager.getClientAddressLine2() + "<br>" + ConfigManager.getClientAddressLine3() + "<br>" + ConfigManager.getClientPhone() + "<br>" + ConfigManager.getClientFax() + "</td>\n");
            buf.append ("<td width='30%'>&nbsp;</td></TR>");
        buf.append ("</table></td></tr>");
        //buf.append ("<tr><td width='40%' align='center'>\n");
        //buf.append ("<td width='30%' colspan='2'>&nbsp;</td>");
        //buf.append ("<td width='15%'>&nbsp;</td></tr>");
         buf.append ("<tr><td align='center'>");
        buf.append ("<table width='100%' border='0' class='NArialR' bordercolor='#000000' cellspacing='0'>");
            buf.append ("<tr><td bgcolor='#FFFFEE' class='NArialR' width='40%' align='left'>");
            buf.append ("<table width='100%' class='NArialR' border='1' bordercolor='#000000' cellspacing='0'>");
            buf.append ("<tr height='30'><td class='NArialR' bgcolor='#DEE1E2' >Ship From:</td></tr>");
            buf.append ("<tr><td>" + ConfigManager.getClientAddressLine1() + "<br>" + ConfigManager.getClientAddressLine2() + "<br>" + ConfigManager.getClientAddressLine3() + "<br><br>");
            buf.append ("<br>" + ConfigManager.getClientPhone() + "<br>" + ConfigManager.getClientFax() + " </td></tr></table></td>");
            buf.append ("<td width='20%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif'></td>");
            buf.append ("<td  width='40%' bgcolor='#FFFFEE' class='NArialR' align='right'>");
            buf.append ("<table width='100%' class='NArialR' border='1' bordercolor='#000000' cellspacing='0'>");
            buf.append ("<tr height='30'><td class='NArialR' bgcolor='#DEE1E2' >Ship To:</td></tr>");
            buf.append ("<tr><td><font class='NArialR'>" + ((packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName()) + "</font><BR>");
            buf.append ("<font class='NArialR'>");
            try
            {
                Address shippingAddress = packingSlipForm.getShippingAddressObject();
                if (shippingAddress == null)
                {
                    shippingAddress = UserDAO.loadAddressById (packingSlipForm.getShippingToAddressId());
                }
                // changed by hareesh on 5th July 2003
                // -- START --
                // Removed the &nbsp; when city or state or country is null
                //system.out.println(" shippingAddress.getAddress1(): "+ shippingAddress.getAddress1());
                buf.append ( (( (shippingAddress.getAddress1() == null) || (shippingAddress.getAddress1().trim().length() == 0) ) ? "" : shippingAddress.getAddress1()+"<BR>") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getAddress2() == null) || (shippingAddress.getAddress2().trim().length() == 0) ) ? "" : shippingAddress.getAddress2()+"<BR>") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getCity() == null) || (shippingAddress.getCity().trim().length() == 0) ) ? "" : shippingAddress.getCity()+",") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getState() == null) || (shippingAddress.getState().trim().length() == 0) ) ? "" : shippingAddress.getState()+",") );
                //buf.append("<BR>");
                buf.append ( (( (shippingAddress.getCountry() == null) || (shippingAddress.getCountry().trim().length() == 0) ) ? "" : shippingAddress.getCountry()+"&nbsp;") );
                //buf.append("&nbsp;");
                // -- END --
                buf.append ( (( (shippingAddress.getZipCode() == null) || (shippingAddress.getZipCode().trim().length() == 0) ) ? "" : shippingAddress.getZipCode()) );
                buf.append("<BR><BR> Ph. ");
                buf.append ( (( (shippingAddress.getPhoneNumber() == null) || (shippingAddress.getPhoneNumber().trim().length() == 0) ) ? "" : shippingAddress.getPhoneNumber()) );
                buf.append("<BR> Fax. ");
                buf.append ( (( (shippingAddress.getFaxNumber() == null) || (shippingAddress.getFaxNumber().trim().length() == 0) ) ? "" : shippingAddress.getFaxNumber()) );

            }
            catch (Exception e)
            {
                System.out.println(" Exception in formatAsHtml: " +e);
            }
            //buf.append ("<font class='NArialL'>" + ((packingSlipForm.getShippingAddress() == null) ? "" : packingSlipForm.getShippingAddress()) + "</font>");
            buf.append ("</font></table></td></tr>");
        buf.append ("</table></td></tr>");

        buf.append ("<tr><td width='100%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='20'></td></tr>");
        /**
        buf.append ("<tr><td width='21%'><font class='NArialL'>PackingSlip Label:</font></td>");
        buf.append ("<td width='21%'><font class='NArialL'><font class='NArialL'>" + ((packingSlipForm.getLabel() == null) ? "" : packingSlipForm.getLabel()) + "</font></td>");
        buf.append ("<td width='3%'>&nbsp;</td><td width='21%'>&nbsp;</td><td width='21%'>&nbsp;</td><td width='3%'>&nbsp;</td></tr>");
        buf.append ("<tr><td width='21%'><font class='NArialL'>Customer PO:</font></td>
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getCustomerPO() == null) ? "" : packingSlipForm.getCustomerPO()) + "</font></td>");
        buf.append ("<td width="3%">&nbsp;</td> <td width="21%"><font class="NArialL">Customer Name:</font></td>
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getCustomerName() == null) ? "" : packingSlipForm.getCustomerName()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td></tr>");
        buf.append ("<tr><td width='21%'><font class='NArialL'>Shipping Contact Person:</font></td>");
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getContactPerson() == null) ? "" : packingSlipForm.getContactPerson()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td><td width='21%'><font class='NArialL'>Rep Office:</font></td>");
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getRepOffice() == null) ? "" : packingSlipForm.getRepOffice()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td></tr>");

        buf.append ("<tr><td width='21%'><font class='NArialL'>Terms</font></td>\n");
        buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getTerms() == null) ? "" : packingSlipForm.getTerms()) + "</font></td>\n");
        buf.append ("<td width='3%'>&nbsp;</td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>FOB</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getFob() == null) ? "" : packingSlipForm.getFob()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
        buf.append ("</tr>\n");

        buf.append ("<tr>\n");
            buf.append ("<td width='21%'><font class='NArialL'>No. Of Boxes</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getNoOfBoxes() == null) ? "" : packingSlipForm.getNoOfBoxes()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");

            buf.append ("<td width='21%'><font class='NArialL'>Tracking</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getTracking() == null) ? "" : packingSlipForm.getTracking()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
       buf.append ("</tr>\n");

       buf.append ("<tr>\n");
            buf.append ("<td width='21%'><font class='NArialL'>Shipped VIA:</font></td>");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.shippedVia() == null) ? "" : packingSlipForm.shippedVia()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
       buf.append ("</tr>\n");

        buf.append ("<tr>\n");
            buf.append ("<td width='21%'><font class='NArialL'>Billing Address</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getBillingAddress() == null) ? "" : packingSlipForm.getBillingAddress()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");

            buf.append ("<td width='21%'><font class='NArialL'>Shipping Address :</font></td>\n");
            buf.append ("<td width='21%'><font class='NArialL'>" + ((packingSlipForm.getShippingAddress() == null) ? "" : packingSlipForm.getShippingAddress()) + "</font></td>\n");
            buf.append ("<td width='3%'>&nbsp;</td>\n");
        buf.append ("</tr>\n");
        **/

        buf.append ("<tr><td width='100%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10'></td></tr>");
         buf.append ("<tr><td width='100%'>\n");
         buf.append ("<table border='1' width='100%' class='NArialR' bordercolor='#000000' cellspacing='0'>\n");
         buf.append ("<TR>\n");
                    buf.append ("<td width='12%' align='center' bgcolor='#DEE1E2'>Customer PO#</td>\n");
                    buf.append ("<td width='12%' align='center' bgcolor='#DEE1E2'>Sales Order#</td>\n");
                    buf.append ("<td width='12%' align='center' bgcolor='#DEE1E2'>Actual Ship Date</td>\n");
                    buf.append ("<td width='20%' align='center' bgcolor='#DEE1E2'>Shipped Via</td>\n");
                    buf.append ("<td width='28%' align='center' bgcolor='#DEE1E2'>Del. Terms</td>");
                    buf.append ("<td width='4%' align='center' bgcolor='#DEE1E2'># Cartons</td>");
                    buf.append ("<td width='12%' align='center' bgcolor='#DEE1E2'>Weight (Lbs)</td>");
                buf.append ("</tr>");
                buf.append ("<tr>");
                    buf.append ("<td width='12%' align='center' bgcolor='#FFFFEE'>"+((packingSlipForm.getCustomerPO() == null) ? "&nbsp;" : packingSlipForm.getCustomerPO())+"</td>");
                    buf.append ("<td width='12%' align='center' bgcolor='#FFFFEE'>"+((packingSlipForm.getSalesOrderNumber() == null) ? "&nbsp;" : packingSlipForm.getSalesOrderNumber())+"</td>");
                    buf.append ("<td width='12%' align='right'  bgcolor='#FFFFEE'>" + ((packingSlipForm.getShipDate() == null) ? "&nbsp;" : packingSlipForm.getShipDate())+"</td>");
                    buf.append ("<td width='20%' align='center' bgcolor='#FFFFEE'>" + ((packingSlipForm.getShippedVia() == null) ? "&nbsp;" : packingSlipForm.getShippedVia())+"&nbsp;</td>");
                    // changed by hareesh on 5th July 2003
                    // -- START --
                    //buf.append ("<td width='28%' align='center' bgcolor='#FFFFEE'>" + ((packingSlipForm.getTerms() == null) ? "&nbsp;" : packingSlipForm.getTerms())+"</td>");
                    buf.append ("<td width='28%' align='center' bgcolor='#FFFFEE'>" + ((packingSlipForm.getFob() == null) ? "&nbsp;" : packingSlipForm.getFob())+"</td>");
                    // -- END --
                    buf.append ("<td width='4%' align='right'  bgcolor='#FFFFEE'>" + ( ((packingSlipForm.getNoOfBoxes() == null) || (packingSlipForm.getNoOfBoxes().equals("0")))? "&nbsp;" : packingSlipForm.getNoOfBoxes())+"</td>");
					String weight = "";
					try
					{
						if ( packingSlipForm.getWeight().trim().length() > 0 )
						{
							weight = StringUtils.formatAmount((float)(new Double(packingSlipForm.getWeight().trim()).doubleValue()), null);
						}
						else
						{
							weight = "&nbsp;";
						}
					}
					catch (Exception e)
					{
						weight = "&nbsp;";
					}
                    buf.append ("<td width='12%' align='right' bgcolor='#FFFFEE'>" + weight +"</td>");
                buf.append ("</tr></table></td></tr>");

        buf.append ("<tr><td  width='100%'><font class='NArialR'><strong><u>Shipping Instructions:</u></strong></font></td></tr>\n");

        buf.append ("<tr><td  bgcolor='#DEE1E2'><font class='NArialR'>" + ((packingSlipForm.getShippingInstructions() == null) ? "" : packingSlipForm.getShippingInstructions()) + "</font></td></tr>\n");

        buf.append ("<tr><td ><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='10' ></td></tr>\n");
     buf.append ("<tr><td  width='100%' >\n");
            buf.append ("<table border='0' width='100%' class='NArialR' bordercolor='#000000' cellspacing='0'>\n");

        buf.append ("<tr><td  width='100%' >\n");
            buf.append ("<table border='1' width='100%' class='NArialL' bordercolor='#000000' cellspacing='0'>\n");

                  buf.append ("<tr>\n");
                    buf.append ("<td width='5%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>PO Line Item</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Mfg Part Number</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Customer Part Number</font></td>");//Bhaskar on 17 December 2003
                    buf.append ("<td width='25%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Description</font></td>");

                    buf.append ("<td width='5%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Unit Type</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Request Date</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Schedule Date</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Req Qty</font></td>");
                    buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialR'>Qty Shipped</font></td>");

                    buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2' nowrap><font class='NArialR'>Lot # Vs Qty</font></td>");
                buf.append ("</tr>\n");

                    //buf.append ("<td width='5%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Line Item</td>");
                    //buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Marketing Part No</td>");
                    //buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Mfg Part No</td>");
                    //buf.append ("<td width='15%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Software Version</td>");
                    //buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Qty Shipped</td>");
                    //buf.append ("<td width='10%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>UoM</td>");
                    //buf.append ("<td width='25%' nowrap align='center' bgcolor='#DEE1E2'><font class='NArialL'>Description</td>");
                    //buf.append ("<td width='20%' nowrap align='center' bgcolor='#DEE1E2' nowrap><font class='NArialL'>Lot Number Vs Qty</td>");
                //buf.append ("</tr>\n");

            /**
                buf.append ("<tr>\n");
                    buf.append ("<td width='4%'  align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Line Item</font></td>\n");
                    buf.append ("<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Marketing Part No</font></td>\n");
                    buf.append ("<td width='25%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Description</font></td>\n");
                    buf.append ("<td width='15%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Manufacturing Part No</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Req. Ship Date</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Sch. Ship Date</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Requested Quantity</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Quantity To be Shipped</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Quantity Shipped</font></td>\n");
                    buf.append ("<td width='8%'  align='center' bgcolor='#993333'><font class='NArialL'><font color='#FFFFFF'>Lot Numbers</font></td>\n");
                buf.append ("</tr>\n");
                **/


        if (orderLineItemList == null) orderLineItemList = new ArrayList();
        if (csLineItemMap == null) csLineItemMap = new HashMap();
        if (finalInventoryMap == null) finalInventoryMap = new HashMap();

	// added by ravikanth on 20 Aug 2003 for sorting by PO Line Item
		Collections.sort(orderLineItemList,new PackingSlipComparator());

        LineItem lineItem = null;
        CustomerShippingLineItem csLineItem = null;
        ArrayList finalInventoryList = null;
        FinalInventoryData finalInventoryData = null;
        int finalInventoryListSize = -1;
        int size = orderLineItemList.size();

		HashMap customerShippingLotNumberMap = null;
		Iterator customerShippingLotNumbers = null;
		CustomerShippingLotNumberData customerShippingLotNumberData = null;

        for (int i=0; i<size; i++) {
            lineItem = (LineItem) orderLineItemList.get (i);
            csLineItem = (CustomerShippingLineItem) csLineItemMap.get (lineItem.getLineItemId()+"");
            finalInventoryList = (ArrayList) finalInventoryMap.get (lineItem.getLineItemId()+"");
            String description = ( ( ( csLineItem.getDescription() == null ) || ( csLineItem.getDescription().trim().length() == 0 ) ) ? lineItem.getDescription() : csLineItem.getDescription());
            String customerPartNumber = ( ( ( csLineItem.getCustomerPartNumber() == null ) || ( csLineItem.getCustomerPartNumber().trim().length() == 0 ) ) ? lineItem.getCustomerPartNumber() : csLineItem.getCustomerPartNumber());//Bhaskar on 17 December 2003
			//system.out.println ("formatAsHTML method in PSA : "+csLineItem.getCustomerPartNumber());
			String version = (csLineItem.getSoftwareVersion() == null ? "" :csLineItem.getSoftwareVersion());
			String units = csLineItem.getUnits();//Bhaskar on 28 Jan 2004
			if((units == null) || ((units != null) && (units.equalsIgnoreCase("null"))))
			units = "";

                buf.append ("<tr>\n");
                    buf.append ("<td width='5%'  align='center' bgcolor='#FFFFEE'><font class='NArialR'>");
                    	if( lineItem.getPoLineItemNo() == 0 )
                    	{
							buf.append ("&nbsp;");
                    	}
					  	else
					  	{
							buf.append (lineItem.getPoLineItemNo());
					  	}
					buf.append ("</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>" + /*lineItem.getMarketingPartNo()*/ lineItem.getManufacturingPartNo() + "</font></td>\n");
					buf.append ("<td width='10%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>" + customerPartNumber + "</font></td>\n");
                    buf.append ("<td width='25%' align='center' bgcolor='#FFFFEE'>");
                    buf.append ("<table border='0' width='100' bgcolor='#FFFFEE' class='viewTable'><tr><td align='center' bgcolor='#FFFFEE'><font class='NArialR'>");
                    buf.append ( ( ( ( description == null ) || ( description.trim().length() == 0 ) ) ? "" : description ) +"</font></td></tr></table></td>");

                    buf.append ("<td width='5%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>" + ( ( units.trim().length() == 0 ) ? "&nbsp;" : units ) + "</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>" + (lineItem.getRequestDate()!=null?lineItem.getRequestDate():"&nbsp;") + "&nbsp;</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>" + (lineItem.getScheduleDate()!=null?lineItem.getScheduleDate():"&nbsp;") + "&nbsp;</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>" + StringUtils.formatUnits ( lineItem.getQuantity() ) + "</font></td>\n");
                    buf.append ("<td width='10%' align='center' bgcolor='#FFFFEE'><font class='NArialR'>");

                    if (csLineItem != null) buf.append ( StringUtils.formatUnits ( csLineItem.getQtyShipped() ) );
                    buf.append ("</font></td>\n");

		            buf.append ("<td width='15%' align='center' bgcolor='#FFFFEE' nowrap><font class='NArialR'>\n");
                    buf.append ("<table bgcolor='#FFFFEE' border='1' bordercolor='#000000' cellspacing='0'  cellpadding='0' width='100%' >\n");

                   	String lotNumbers = "";

					try {
                    	customerShippingLotNumberMap = PackingSlipDAO.loadCustomerShippingLotNumberData (packingSlipForm.getCustomerShippingId(), lineItem.getLineItemId());
					}
					catch (ScalarException se) {
						System.out.println ("Exception while load customer shipping lot number data from database");
						se.printStackTrace();
					}

					if (customerShippingLotNumberMap == null) customerShippingLotNumberMap = new HashMap();

					customerShippingLotNumbers = customerShippingLotNumberMap.values().iterator();

					int qtyPull = 0;
					while (customerShippingLotNumbers.hasNext()) {
						customerShippingLotNumberData = (CustomerShippingLotNumberData) customerShippingLotNumbers.next();
						qtyPull = customerShippingLotNumberData.getQtyPull();

						if (qtyPull > 0) {

							buf.append ("<tr>");
							buf.append ("<td nowrap><font class='NArialR'>" + customerShippingLotNumberData.getLotNumber() + "</font></td>");
							buf.append ("<td nowrap><font class='NArialR'>" + qtyPull + "</font></td>");
							buf.append ("</tr>");
						}
					}

                    buf.append ("</table></font></td>\n");

					/*
                        String lotNumbers = "";
                        if (finalInventoryList == null) {
                            try {
                                finalInventoryList = FinalInventoryDAO.loadFinalInventoryData (lineItem.getMarketingPartNo());
                            }
                            catch (ScalarException se) {
                                // Couldnt load FinalInventoryData List from databse... ignore
                            }
                        }

                        if (finalInventoryList != null) {
                            finalInventoryListSize = finalInventoryList.size();

                            for (int j=0; j<finalInventoryListSize; j++) {
                                finalInventoryData = (FinalInventoryData) finalInventoryList.get (j);

                                if (finalInventoryData != null) {
                                    lotNumbers += finalInventoryData.getLotNumber() + "<br>";
                                }
                            }
                        }

                buf.append ("<td width='8%' align='center' bgcolor='#DEE1E2'><font class='NArialL'><%=lotNumbers%></font></td>\n");
                */
            buf.append ("</tr>\n");

        }   // for (int i=0; i<size; i++)

            //buf.append ("<tr><td colspan=6><img src='http://" + host + "/" + ConfigManager.getChipTracContext() +"/jsp/includes/images/spacer.gif' height='60' ></td></tr>\n");
               // buf.append ("<tr><td colspan=9><BR></td></tr>\n");
	   buf.append ("</table></td></tr>\n");

        buf.append ("<tr><td ><BR></td></tr>\n");
		/*
		This block is added by Bhaskar on 28 Jan 2004 begin
		*/
        buf.append ("<tr><td colspan=4>");
		buf.append("<table border='0' width='100%' align='center' bordercolor='#FFFFFF' cellspacing='2' cellpadding='2'>");
		buf.append("<tr><td align='center'><font class='NArialView'>CERTIFICATE OF COMPLIANCE</font></td></tr>");
		buf.append("<tr><td><font class='NArialRS'>THIS PRODUCT SHIPPED HERE WITH HAVE BEEN INSPECTED AND COMPLY WITH THE "+
		"REQUIREMENTS OF YOUR PURCHASE ORDER TO THE EXTENT THAT SUCH REQUIREMENT HAVE BEEN ACCEPTED AND ACKNOWLEDGED BY "+
		"CAVIUM SUBSTANTIATING INSPECTION AND TEST ON THAT FILE.</font></td></tr>");
		buf.append ("<tr><td align='center'><font class='NArialRS'><B>THANK YOU FOR YOUR BUSINESS!</B></font></td></tr></table>");
        buf.append ("</td></tr>\n");
		/*
		This block is added by Bhaskar on 28 Jan 2004 ends
		*/
        buf.append ("<tr><td ><BR></td></tr>\n");

        //buf.append ("<tr>\n");
          //  buf.append ("<td bgcolor='silver' colspan=3 class='NArialL' valign='top' align='top'>Customer Note:</td>\n");
           // buf.append ("<td>&nbsp;</td>\n");
            //buf.append ("<td bgcolor='silver' colspan=2 class='NArialL' valign='top' align='top'>Received By:</td>\n");
        //buf.append ("</tr>\n");
        buf.append ("<tr><td width='100%'><table width='100%'>\n");
        buf.append ("<tr>\n");
            buf.append ("<td class='NArialR' width='35%'><b>Packer:</b> </td>\n");
            buf.append ("<td class='NArialR' width='35%'>__________________________________________</td>");
            buf.append ("<td width='30%'>&nbsp;</td>");
        buf.append ("</tr>\n");
        buf.append ("</table></td></tr>\n");
        buf.append ("<tr><td width='100%'><table width='100%'>\n");

        buf.append ("<tr>\n");
            buf.append ("<td class='NArialR' width='35%'><b>Hand Carry Receipt</b>\n");
            buf.append ("<td class='NArialR' width='35%'>__________________________________________<br> <b>Signature & Title</b>");
            buf.append ("<td width='30%'>&nbsp;</td>");

        buf.append ("</table></td></tr>\n");
        buf.append ("<tr><td width='100%'><table width='100%'>\n");

        buf.append ("<tr>\n");
            buf.append ("<td class='NArialR' width='35%'>&nbsp;\n");
            buf.append ("<td class='NArialR' width='35%'>__________________________________________<br> <b>Print Name & Date</b> ");
            buf.append ("<td width='30%'>&nbsp;</td>\n");
        buf.append ("</tr>\n");
        buf.append ("</table></td></tr>\n");

        buf.append ("</table>\n");

        buf.append ("<!-- till here -->\n");

       // buf.append ("</TD></TR>\n");
        //buf.append ("</TABLE>\n");

        buf.append ("</body>\n");

        buf.append ("</html>\n");


        return buf.toString();
    }


    /**
     *@return creates a temporary PackingSlip HTML form, and returns the absolute path
     */
    public String getPackingSlipAsHtmlFile( String host, PackingSlipForm packingSlipForm, ArrayList orderLineItemList, HashMap csLineItemMap, HashMap finalInventoryMap)
    {
        String filePath = null;
        String psAsHtml = formatAsHTML(host, packingSlipForm, orderLineItemList, csLineItemMap, finalInventoryMap);

        if( psAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try {
            // CREATE TEMPORARY ATTACHMENT FILE
            File tempDir = new File ("chiptrac_temp_dir").getCanonicalFile();
            tempDir.mkdir();

            // Packing Slip Attachment File Name - Start    -- Balaram, July 1, 2003
            String psAttachmentFileName = packingSlipForm.getLabel();
            if( ( psAttachmentFileName != null ) && ( psAttachmentFileName.startsWith( "PS-" ) ) )
            {
                // Changed by hareesh on 27th August 2003
                //psAttachmentFileName = "Packing_Slip_SO#" + psAttachmentFileName.substring( 3 );
                psAttachmentFileName = psAttachmentFileName.substring( 3 );
            }

            // Changed by hareesh on 27th August 2003
            //psAttachmentFileName = psAttachmentFileName + ".html";
            psAttachmentFileName = "Packing_Slip_SO#" + psAttachmentFileName + ".html";
            // Packing Slip Attachment File Name - END -- Balaram, July 1, 2003

            psAttachment = new File( tempDir.getCanonicalPath(), psAttachmentFileName );
            psAttachment.deleteOnExit();

            if( ( psAttachment.exists() == true ) || ( psAttachment.createNewFile() == true ) )
            {
                fWriter = new FileWriter (psAttachment, false);

                fWriter.write( psAsHtml );

                fWriter.close();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath();
            }
        }
        catch( Exception e )
        {
            System.out.println( "Exception while creating packingslip html file");
            e.printStackTrace();
        }
        finally
        {
            if( fWriter != null )
            {
                try
                {
                    fWriter.close();
                    fWriter = null;
                }
                catch( IOException ignore ){}
            }
        }

        return filePath;
    }


    public void sendPackingSlipMail (String from, String to, String subject, String message, String packingSlipAsHTML, HttpServletRequest request) {

        FileWriter fWriter = null;
        File psAttachment = null;
        try {
            // CREATE TEMPORARY ATTACHMENT FILE
            File tempDir = new File ("packingslip_temp_dir").getCanonicalFile();
            tempDir.mkdir();

            psAttachment = new File (tempDir.getCanonicalPath(), "Packingslip" + System.currentTimeMillis() + ".html");
            psAttachment.deleteOnExit();

            if ((psAttachment.exists() == true) || (psAttachment.createNewFile() == true)) {
                fWriter = new FileWriter (psAttachment, false);
                fWriter.write (packingSlipAsHTML);
                fWriter.close();
                fWriter = null;

                // SEND MAIL
                Mailer.send (from, to, null/*cc*/, null/*bcc*/, subject, message, new String[]{psAttachment.getAbsolutePath()}, Mailer.CONTENT_TYPE_HTML, false /*send mail to all email*/);
                //system.out.println ("Packing Slip information has been sent to " + to);
            }
        }
        catch (Exception e) {
            System.out.println ("Could not send mail to: " + to + ", System Exception - " + e);
            //HashMap errors = new HashMap();
            m_errors.put ("Could not send a mail", null );
            request.setAttribute (SessionKeys.ERROR_MESSAGES, m_errors);
        }
        finally {
            if (fWriter != null) {
                try { fWriter.close(); } catch (IOException ignore) {}
            }

            // DELETE THE TEMPORARY ATTACHMENT FILE
            if (psAttachment != null) {
                psAttachment.delete();
            }
        }
    }


	private void repeatedPartNumbers ( ArrayList orderLineItemList, HttpSession session )
	{
		ArrayList repetedPartNumber = new ArrayList();
		if( orderLineItemList.size() > 1)
		{
			for( int i=0 ; i < orderLineItemList.size()-1 ; i++ )
			{
				LineItem lineItem = (LineItem) orderLineItemList.get(i);
				String partNumber = lineItem.getManufacturingPartNo();

				for(int j=i+1 ; j < orderLineItemList.size(); j++)
				{
					LineItem secLineItem = (LineItem) orderLineItemList.get(j);

					String secPartNumber = secLineItem.getManufacturingPartNo();

					if(partNumber.equalsIgnoreCase(secPartNumber))
					{
						if( !repetedPartNumber.contains(lineItem.getLineItemId()+"") )
							repetedPartNumber.add(lineItem.getLineItemId()+"");
						if( !repetedPartNumber.contains(secLineItem.getLineItemId()+"") )
							repetedPartNumber.add(secLineItem.getLineItemId()+"");
					}
				}
			}
		}
		if( repetedPartNumber.size() > 0 )
		{
			session.setAttribute("repetedPartNumber",repetedPartNumber);
		}
	}
}